package com.learning.servlet2x.filter;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * ClassName: CustomFilter
 * Description: 自定义Filter
 * 1、实现 `javax.servlet.Filter` 接口
 * 2、实现其 init、doFilter、destroy 三个方法
 * Date: 2014-10-12 21:16 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0 效，
 */
public class CustomFilter implements Filter {

    public CustomFilter() {
    }

    @PostConstruct
    public void postConstruct() {
    }


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String name = filterConfig.getInitParameter("name");
        System.out.println("获取过滤器的初始化参数： " + name);
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        //上下文路径
        String contextPath = request.getContextPath();
        //得到访问的servlet或者jsp的路径
        String servletPath = request.getServletPath();

        System.out.println("上下文路径:" + contextPath);
        System.out.println("访问的servlet或者jsp的路径 ： " + servletPath);

        chain.doFilter(req, resp);
    }

    @Override
    public void destroy() {

    }

    @PreDestroy
    public void PreDestroy() {

    }


}
